package server.core;

import lombok.Data;
import lombok.SneakyThrows;
import org.dom4j.Node;
import server.RequestProcessor;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

@Data
public class Connector {
    private int port;
    private List<Host> hostList;
    public Connector(Node connectorNode) {
        port = Integer.parseInt(connectorNode.valueOf("@port"));
    }

    public void init(List<Host> hostList) {
        this.hostList = hostList;
    }

    @SneakyThrows
    public void start() {
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + serverSocket.getLocalPort());
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, hostList);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


}
